<template>
  <div class="user-management-container">
    <div class="page-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <div class="search-area">
          <el-input
            v-model="searchQuery"
            placeholder="输入用户名搜索"
            prefix-icon="Search"
            :style="{ width: '240px' }"
            @keyup.enter="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="clearSearch">清空</el-button>
        </div>
      </div>
    </div>

    <div class="table-container">
      <div class="action-buttons">
        <el-button type="primary" icon="Plus" @click="handleAddUser">
          添加用户
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="usersList"
        :default-sort="{ prop: 'id', order: 'ascending' }"
      >
        <!-- 添加序号列 -->
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="username"
          label="用户名"
          width="180"
          align="center"
        />
        <el-table-column
          prop="userType"
          label="用户角色"
          width="140"
          align="center"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.userType === 'admin' ? 'primary' : 'success'"
              >{{
                scope.row.userType === "admin" ? "管理员" : "普通用户"
              }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.registerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        size="small"
        background
        layout="sizes, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加用户弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加用户"
      width="400px"
      :before-close="handleClose"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="userType">
          <el-radio-group v-model="userForm.userType">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="400px"
      :before-close="handleEditClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="不修改请留空"
            show-password
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="userType">
          <el-radio-group v-model="editForm.userType">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="admin">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleEditClose">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getUserList } from "../../api/user";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { register } from "../../api/user";
import { updateUser } from "../../api/user";
import { deleteUser } from "../../api/user";

const usersList = ref([]);
const currentPage = ref(1);
const total = ref(0);
const pageSize = ref(10);
const searchQuery = ref("");
const loading = ref(false);

const dialogVisible = ref(false);
const userFormRef = ref(null);
const userForm = ref({
  username: "",
  password: "",
  userType: "user",
});
const userRules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度在 3 到 20 个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
});

// 编辑用户相关状态
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = ref({
  id: "",
  username: "",
  password: "",
  userType: "user",
});
const editRules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度在 3 到 20 个字符",
      trigger: "blur",
    },
  ],
  password: [
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
  ],
});

// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return "-";
  return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
};

const getUsersList = async () => {
  loading.value = true;
  try {
    const res = await getUserList({
      page: currentPage.value,
      pageSize: pageSize.value,
      username: searchQuery.value,
    });
    // console.log("API返回结果:", res);
    // 处理响应数据
    if (res && res.code === 0) {
      usersList.value = res.data || [];
      total.value = res.total || 0;
    } else {
      usersList.value = [];
      total.value = 0;
    }
    // console.log("处理后的数据列表:", usersList.value);
    // console.log("总条数:", total.value);
  } catch (error) {
    console.error("获取用户列表失败:", error);
    usersList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getUsersList();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getUsersList();
};

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1;
  getUsersList();
};
// 清空搜索
const clearSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1;
  getUsersList();
};

// 添加用户
const handleAddUser = () => {
  // 重置表单
  userFormRef.value?.resetFields();
  dialogVisible.value = true;
};
// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};
// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    await userFormRef.value.validate();
    // 显示加载状态
    loading.value = true;
    // 调用注册接口添加用户
    const { username, password } = userForm.value;
    await register(username, password);
    // 关闭弹窗
    dialogVisible.value = false;
    // 刷新用户列表
    await getUsersList();
    // 提示成功
    ElMessage.success("用户添加成功");
  } catch (error) {
    console.error("添加用户失败:", error);
    ElMessage.error("添加用户失败");
  } finally {
    loading.value = false;
  }
};

//编辑用户
const handleEdit = (row) => {
  console.log("编辑用户:", row);
  // 填充表单数据
  editForm.value = {
    id: row.id,
    username: row.username,
    password: "", // 密码留空，不修改
    userType: row.userType,
  };
  editDialogVisible.value = true;
};

// 关闭编辑弹窗
const handleEditClose = () => {
  editDialogVisible.value = false;
};

// 提交编辑表单
const handleEditSubmit = async () => {
  try {
    // 验证表单
    await editFormRef.value.validate();
    // 显示加载状态
    loading.value = true;
    // 调用更新用户接口
    await updateUser(editForm.value);
    // 关闭弹窗
    editDialogVisible.value = false;
    // 刷新用户列表
    await getUsersList();
    // 提示成功
    ElMessage.success("用户编辑成功");
  } catch (error) {
    console.error("编辑用户失败:", error);
    ElMessage.error("编辑用户失败");
  } finally {
    loading.value = false;
  }
};

const handleDelete = async (row) => {
  try {
    // 显示确认弹窗
    const confirm = await ElMessageBox.confirm("确认删除用户吗？", "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // 调用删除接口
    await deleteUser(row.id);
    // 刷新用户列表
    await getUsersList();
    // 提示成功
    ElMessage.success("用户删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除用户失败:", error);
      ElMessage.error("删除用户失败");
    }
  }
};

onMounted(() => {
  getUsersList();
});
</script>

<style lang="less" scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeef3;
}

.header-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.search-area {
  display: flex;
  gap: 10px;
}

.table-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

// 修复固定列导致的表格不完整问题
::v-deep .el-table {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

// 确保表格容器与内容正确对齐
::v-deep .el-table__body-wrapper {
  width: 100% !important;
}

::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center !important;
}
</style>
